package com.arvts.android.project;

import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.arvts.android.project.adapter.ConnectionDetector;
import com.arvts.android.project.adapter.SharedPreferencesClass;
import com.arvts.android.project.data.VehicleDS;
import com.arvts.android.project.model.Vehicle;

public class Login extends Activity implements OnClickListener {
	EditText txtUsername;
	EditText txtPassword;
	
	ProgressDialog dialog;
	int TIMEOUT_MILLISEC = 10000;
	EditText t1, t2,areaCode,etEmail;
	String s = "";
	JSONObject jObject;
	
	public static final String SETTINGS = "SETTINGS";
	SharedPreferences localSP;
	Button btnLogin;
	//----Test server URL-----
	public static String IP="http://server.arvts.com/~vts24/webservice/";//check_user.php
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_login);
		
		localSP = getSharedPreferences(SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		
		txtUsername = (EditText) findViewById(R.id.et_username);
		txtUsername.requestFocus();
		txtPassword = (EditText) findViewById(R.id.et_password);
		btnLogin = (Button) findViewById(R.id.b_login);
		btnLogin.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		String username = txtUsername.getText().toString();
		String password = txtPassword.getText().toString();
		
		boolean connectionStatus = new ConnectionDetector(getApplicationContext()).isConnectingToInternet();
		
		if(connectionStatus == true){
			
			if (!(username.equals("") && password.equals(""))) {
				
				new check_user().execute();
				
			}else{
				Toast.makeText(Login.this, "Invaild username or/and password",Toast.LENGTH_LONG).show();
			}
			
		}else
			Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
			
			
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}
	
	class check_user extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(Login.this);
			dialog.setMessage("Please wait...");
			dialog.setIndeterminate(false);
			dialog.setCancelable(false);
			dialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			try {
			
				JSONObject json = new JSONObject();
				json.put("username", txtUsername.getText().toString());
				json.put("password",  txtPassword.getText().toString());
				

				HttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
				HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
				HttpClient httpclient = new DefaultHttpClient(httpParams);

				String url = IP + "check_user.php";

				HttpPost request = new HttpPost(url);

				request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
				request.setHeader("json", json.toString());

				ResponseHandler<String> responseHandler = new BasicResponseHandler();

				String responseBody = httpclient.execute(request,responseHandler);

				// Parse
				JSONObject json1 = new JSONObject(responseBody);
				JSONArray jArray = json1.getJSONArray("posts");

				for (int i = 0; i < jArray.length(); i++) {

					JSONObject e = jArray.getJSONObject(i);
					s = e.getString("post");
					jObject = new JSONObject(s);

					if (jObject.getString("tot_count").equals("1")) {
						
						Log.v("Success", "Login Success");				
						SharedPreferencesClass.setLocalSharedPreference(getApplicationContext(), "user_id",jObject.getString("user_id"));
						
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			dialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
	
					try {
						if (jObject.getString("tot_count").equals("0")) {
							
							Toast.makeText(Login.this, "Invaild username or/and password",Toast.LENGTH_LONG).show();
							
						}else if(jObject.getString("tot_count").equals("1")) {
							
							new downloadVehileDetails().execute(jObject.getString("user_id"));
							
						}
					} catch (Exception e) {
						Toast.makeText(
								Login.this,
								"Network connection currently unavailable.!! Please check your network connection.",
								Toast.LENGTH_LONG).show();
					}

				}
			});

		}

	}
	
	class downloadVehileDetails extends AsyncTask<String, String, ArrayList<Vehicle>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(Login.this);
			dialog.setMessage("Downloading data...");
			dialog.setIndeterminate(false);
			dialog.setCancelable(false);
			dialog.show();
		}


		protected ArrayList<Vehicle> doInBackground(String... args) {
			
			ArrayList<Vehicle> list= new ArrayList<Vehicle>();
			
			try {
			
				JSONObject json = new JSONObject();
				json.put("Id", args[0]);
				
				HttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
				HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
				HttpClient httpclient = new DefaultHttpClient(httpParams);

				String url = IP + "get_vehicle.php";

				HttpPost request = new HttpPost(url);

				request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
				request.setHeader("json", json.toString());

				ResponseHandler<String> responseHandler = new BasicResponseHandler();

				String responseBody = httpclient.execute(request,responseHandler);

				// Parse
				JSONObject json1 = new JSONObject(responseBody);
				JSONArray jArray = json1.getJSONArray("posts");

				
				
				
 				for (int i = 0; i < jArray.length(); i++) {

					JSONObject e = jArray.getJSONObject(i);
					s = e.getString("post");
					jObject = new JSONObject(s);
					
					Vehicle vehicle=new Vehicle();
					
					vehicle.setVEHICLE_ID(jObject.getString("id"));
					vehicle.setVEHICLE_SERVICE_DURATION(jObject.getString("service_duration"));
					vehicle.setVEHICLE_IDLE_TIME_LIMIT(jObject.getString("idle_time_limit"));
					vehicle.setVEHICLE_NUMBER(jObject.getString("vehicle_number"));
					vehicle.setVEHICLE_DEVICE_PASSWORD(jObject.getString("device_password"));
					vehicle.setVEHICLE_TYPE(jObject.getString("vehicle_type"));
					vehicle.setVEHICLE_LOCK_STATUS(jObject.getString("lock_status"));
					vehicle.setVEHICLE_LOCKED_DATE(jObject.getString("locked_date"));
					vehicle.setVEHICLE_DATE_CREATED(jObject.getString("date_created"));
					vehicle.setVEHICLE_SECONDARY_PHONE_NUMBER(jObject.getString("secondary_phone_numbers"));
					vehicle.setVEHICLE_SERVICE_MILEAGE(jObject.getString("service_mileage"));
					vehicle.setVEHICLE_INITIAL_MILEAGE_READING(jObject.getString("initial_mileage_reading"));
					vehicle.setVEHICLE_DEVICE_PHONE_NUMBER(jObject.getString("device_phone_number"));
					
					list.add(vehicle);
					
					Log.v("heelo22", s);


				}
			} catch (Exception e) {

				e.printStackTrace();
			}

			
			return list;
		}


		protected void onPostExecute(final ArrayList<Vehicle> arrayList) {
			// dismiss the dialog after getting all products
			dialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
	
					try {
						VehicleDS ds =new VehicleDS(Login.this);
						
						int count=ds.createOrUpdateArea(arrayList);
						Log.v("Inseting status",count+"");
						
						if(count>0){
							Intent mainActivity = new Intent(Login.this,ListOfVehicleNo.class);
							startActivity(mainActivity);
							Toast.makeText(Login.this, "You have been successfully logged in!",Toast.LENGTH_LONG).show();
							
							//VehicleDetialsDialogbox();
						}
						
					} catch (Exception e) {
						Log.v("Error inseting", e.toString());
					}

				}
			});

		}

//public void VehicleDetialsDialogbox()
//		{		
//			final Dialog dialog = new Dialog(Login.this);
//			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//			dialog.setContentView(R.layout.vehicle_list_layout);
//			
//			final ListView list=(ListView) dialog.findViewById(R.id.listView1); 
//			
//			
//			dialog.setCancelable(false);
//			
//			VehicleDS vehicleDS=new VehicleDS(Login.this);
//			list.clearTextFilter();
//			
//			final ArrayList<Vehicle> arrayList= vehicleDS.getAllVehicleDetails();
//			list.setAdapter(new VehicleDetailsAdapter(Login.this, arrayList));
//
//			list.setOnItemClickListener(new OnItemClickListener() {
//
//				@Override
//				public void onItemClick(AdapterView<?> parent, View view,
//						int position, long id) {
//					
//					Vehicle vehicle = arrayList.get(position);					
//					
//					Log.v("Selected Vehicle No. ", vehicle.getVEHICLE_NUMBER());
//					
//					dialog.dismiss();
//				}
//			});
//				
//			dialog.show();
//		}	
		
	}
}
